---
import ContainedSection from "#/components/ContainedSection.astro"
import TextP from "#/components/typography/TextP.astro"
import AnimationLayout from "#/layouts/AnimationLayout.astro"
import { contentfulClient } from "#/lib/contentful/client.ts"
import type {
  RoadmapMilestoneFields,
  RoadmapMilestoneSkeleton,
  RoadmapSectionFields,
  RoadmapSectionSkeleton,
  RoadmapSubsectionFields,
  RoadmapSubsectionSkeleton,
} from "#/lib/contentful/types.ts"

export const prerender = false

// Fetch all roadmap data from Contentful
let sectionsData: any[] = []
let subsectionsData: any[] = []
let milestonesData: any[] = []
let error: string | null = null

try {
  // Fetch all sections
  const sectionsResponse = await contentfulClient.getEntries<RoadmapSectionSkeleton>({
    content_type: "roadmapSection",
    order: ["fields.position"],
  })
  sectionsData = sectionsResponse.items.map(item => ({
    ...item.fields,
    id: item.sys.id,
  }))

  // Fetch all subsections with linked sections
  const subsectionsResponse = await contentfulClient.getEntries<RoadmapSubsectionSkeleton>({
    content_type: "roadmapSubsection",
    order: ["fields.position"],
    include: 2,
  })

  subsectionsData = subsectionsResponse.items.map(item => {
    // The linkedSection field contains the reference
    const linkedSectionId = (item.fields.linkedSection as any)?.sys?.id
    return {
      ...item.fields,
      id: item.sys.id,
      linkedSectionId: linkedSectionId,
    }
  })

  // Fetch all milestones with asset data
  const milestonesResponse = await contentfulClient.getEntries<RoadmapMilestoneSkeleton>({
    content_type: "roadmapMilestone",
    order: ["fields.position"],
    include: 3,
    limit: 1000,
  })

  milestonesData = milestonesResponse.items.map(item => ({
    ...item.fields,
    id: item.sys.id,
    linkedSubsectionId: item.fields.linkedSubsection?.sys?.id,
    // Include the full asset objects
    completeIcon: item.fields.completeIcon,
    incompleteIcon: item.fields.incompleteIcon,
  }))
} catch (err) {
  console.error("Error fetching roadmap data from Contentful:", err)
  error = "Failed to load roadmap content. Please try again later."
}

// Group data hierarchically
const roadmapData = sectionsData.map(section => {
  const sectionSubsections = subsectionsData
    .filter(sub => sub.linkedSectionId === section.id)
    .map(subsection => {
      const subsectionMilestones = milestonesData
        .filter(milestone => milestone.linkedSubsectionId === subsection.id)
        .sort((a, b) => (a.position || 0) - (b.position || 0))

      return {
        ...subsection,
        milestones: subsectionMilestones,
      }
    })
    .sort((a, b) => (a.position || 0) - (b.position || 0))

  return {
    ...section,
    subsections: sectionSubsections,
  }
}).sort((a, b) => (a.position || 0) - (b.position || 0))

// Calculate overall progress
const calculateProgress = (section: any) => {
  if (section.percentComplete !== undefined && section.percentComplete !== null) {
    return section.percentComplete
  }

  if (section.subsections && section.subsections.length > 0) {
    const totalProgress = section.subsections.reduce((acc: number, sub: any) => {
      if (sub.percentComplete !== undefined && sub.percentComplete !== null) {
        return acc + sub.percentComplete
      }
      if (sub.milestones && sub.milestones.length > 0) {
        const completedMilestones = sub.milestones.filter((m: any) => m.markComplete).length
        return acc + (completedMilestones / sub.milestones.length) * 100
      }
      return acc
    }, 0)
    return Math.round(totalProgress / section.subsections.length)
  }

  return 0
}

// Calculate subsection progress
const calculateSubsectionProgress = (subsection: any) => {
  if (subsection.percentComplete !== undefined && subsection.percentComplete !== null) {
    return subsection.percentComplete
  }

  if (subsection.milestones && subsection.milestones.length > 0) {
    const completedMilestones = subsection.milestones.filter((m: any) => m.markComplete).length
    return Math.round((completedMilestones / subsection.milestones.length) * 100)
  }

  return 0
}

// Determine status based on progress
const getStatus = (progress: number) => {
  if (progress === 100) {
    return "completed"
  }
  if (progress > 0) {
    return "in-progress"
  }
  return "upcoming"
}

const getStatusColor = (status: string) => {
  switch (status) {
    case "completed":
      return "text-green-500"
    case "in-progress":
      return "text-yellow-500"
    case "upcoming":
      return "text-zinc-400"
    default:
      return "text-zinc-400"
  }
}
---

<AnimationLayout
  title="Roadmap"
  text="Our journey towards universal interoperability"
>
  <ContainedSection className="overflow-visible">
    {
      error ? (
        <div class="error-message text-center">
          <h2 class="text-2xl font-bold mb-4">Error</h2>
          <p>{error}</p>
        </div>
      ) : (
        <div class="roadmap-container mt-4">
          {/* Mobile Navigation - Top */}
          <div class="lg:hidden mb-6">
            <div class="bg-black p-4 border border-zinc-700 shadow-lg">
              <div class="flex items-center gap-2 mb-4 pb-2 border-b border-zinc-800">
                <div class="w-1 h-1 bg-accent-500"></div>
                <h3 class="font-mono uppercase text-sm font-semibold text-accent-500">
                  Navigation
                </h3>
              </div>
              <nav class="space-y-2">
                {
                  roadmapData.map((section, sectionIndex) => {
                const sectionProgress = calculateProgress(section)
                const sectionStatus = getStatus(sectionProgress)

                return (
                    <div class="section-nav">
                      <div class="flex items-center hover:bg-zinc-800 transition-all group">
                        <button
                          data-section-id={section.id}
                          class="section-nav-item flex-1 text-left px-3 py-2 transition-all"
                        >
                          <div class="flex items-center gap-2">
                            <span class="font-semibold text-sm font-mono uppercase">{
                              section.section
                            }</span>
                            <div class="flex items-center gap-1">
                              <div
                                class={`w-2 h-2 ${
                                  sectionStatus === "completed"
                                    ? "bg-accent-500"
                                    : sectionStatus === "in-progress"
                                    ? "bg-white"
                                    : "bg-zinc-600"
                                }`}
                              >
                              </div>
                              <span class="text-xs text-zinc-400">{sectionProgress}%</span>
                            </div>
                          </div>
                        </button>
                        {
                          section.subsections && section.subsections.length > 0
                    && (
                            <button
                              data-toggle-section={section.id}
                              class="section-toggle p-2 transition-all"
                              title="Toggle subsections"
                            >
                              <svg
                                class="w-4 h-4 toggle-icon transition-transform duration-200 ease-linear"
                                class:list={[sectionIndex === 0 ? "rotate-180" : ""]}
                                fill="currentColor"
                                viewBox="0 0 20 20"
                              >
                                <path
                                  fill-rule="evenodd"
                                  d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                                  clip-rule="evenodd"
                                />
                              </svg>
                            </button>
                          )
                        }
                      </div>

                      {
                        section.subsections && section.subsections.length > 0
                  && (
                          <div
                            class="subsection-nav ml-4 mt-1 space-y-1 transition-all duration-300 ease-in-out overflow-hidden"
                            class:list={[sectionIndex === 0 ? "" : "hidden"]}
                            data-subsections={section.id}
                          >
                            {
                              section.subsections.map((subsection: any) => {
                    const subsectionProgress = calculateSubsectionProgress(
                      subsection,
                    )
                    const subsectionStatus = getStatus(subsectionProgress)

                    return (
                                <button
                                  data-subsection-id={subsection.id}
                                  class="subsection-nav-item w-full text-left px-3 py-1.5 transition-all text-sm hover:bg-zinc-800 block"
                                >
                                  <div class="flex items-center justify-between w-full">
                                    <span class="text-zinc-400 text-xs font-mono">{
                                      subsection.subsection
                                    }</span>
                                    <div class="flex items-center gap-1">
                                      <div
                                        class={`w-1.5 h-1.5 ${
                                          subsectionStatus === "completed"
                                            ? "bg-accent-500"
                                            : subsectionStatus === "in-progress"
                                            ? "bg-white"
                                            : "bg-zinc-600"
                                        }`}
                                      >
                                      </div>
                                      <span class="text-xs text-zinc-500">{
                                          subsectionProgress
                                        }%</span>
                                    </div>
                                  </div>
                                </button>
                              )
                  })
                            }
                          </div>
                        )
                      }
                    </div>
                  )
              })
                }
              </nav>
            </div>
          </div>

          <div class="roadmap-layout flex gap-8">
            {/* Desktop Sidebar Navigation */}
            <aside class="roadmap-sidebar w-80 flex-shrink-0 hidden lg:block sticky top-4 self-start">
              <div class="bg-black p-4 border border-zinc-700 shadow-lg max-h-[calc(100vh-2rem)] overflow-y-auto">
                <div class="flex items-center gap-2 mb-4 pb-2 border-b border-zinc-800">
                  <div class="w-1 h-1 bg-accent-500"></div>
                  <h3 class="font-mono uppercase text-sm font-semibold text-accent-500">
                    Navigation
                  </h3>
                </div>
                <nav class="space-y-2">
                  {
                    roadmapData.map((section, sectionIndex) => {
                  const sectionProgress = calculateProgress(section)
                  const sectionStatus = getStatus(sectionProgress)

                  return (
                      <div class="section-nav">
                        <div class="flex items-center hover:bg-zinc-800 transition-all group">
                          <button
                            data-section-id={section.id}
                            class="section-nav-item flex-1 text-left px-3 py-2 transition-all"
                          >
                            <div class="flex items-center gap-2">
                              <span class="font-semibold text-sm font-mono uppercase">{
                                section.section
                              }</span>
                              <div class="flex items-center gap-1">
                                <div
                                  class={`w-2 h-2 ${
                                    sectionStatus === "completed"
                                      ? "bg-accent-500"
                                      : sectionStatus === "in-progress"
                                      ? "bg-white"
                                      : "bg-zinc-600"
                                  }`}
                                >
                                </div>
                                <span class="text-xs text-zinc-400">{sectionProgress}%</span>
                              </div>
                            </div>
                          </button>
                          {
                            section.subsections && section.subsections.length > 0
                      && (
                              <button
                                data-toggle-section={section.id}
                                class="section-toggle p-2 transition-all"
                                title="Toggle subsections"
                              >
                                <svg
                                  class="w-4 h-4 toggle-icon transition-transform duration-200 ease-linear"
                                  class:list={[sectionIndex === 0 ? "rotate-180" : ""]}
                                  fill="currentColor"
                                  viewBox="0 0 20 20"
                                >
                                  <path
                                    fill-rule="evenodd"
                                    d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
                                    clip-rule="evenodd"
                                  />
                                </svg>
                              </button>
                            )
                          }
                        </div>

                        {
                          section.subsections && section.subsections.length > 0
                    && (
                            <div
                              class="subsection-nav ml-4 mt-1 space-y-1 transition-all duration-300 ease-in-out overflow-hidden"
                              class:list={[sectionIndex === 0 ? "" : "hidden"]}
                              data-subsections={section.id}
                            >
                              {
                                section.subsections.map((subsection: any) => {
                      const subsectionProgress = calculateSubsectionProgress(
                        subsection,
                      )
                      const subsectionStatus = getStatus(subsectionProgress)

                      return (
                                  <button
                                    data-subsection-id={subsection.id}
                                    class="subsection-nav-item w-full text-left px-3 py-1.5 transition-all text-sm hover:bg-zinc-800 block"
                                  >
                                    <div class="flex items-center justify-between w-full">
                                      <span class="text-zinc-400 text-xs font-mono">{
                                        subsection.subsection
                                      }</span>
                                      <div class="flex items-center gap-1">
                                        <div
                                          class={`w-1.5 h-1.5 ${
                                            subsectionStatus === "completed"
                                              ? "bg-accent-500"
                                              : subsectionStatus === "in-progress"
                                              ? "bg-white"
                                              : "bg-zinc-600"
                                          }`}
                                        >
                                        </div>
                                        <span class="text-xs text-zinc-500">{
                                            subsectionProgress
                                          }%</span>
                                      </div>
                                    </div>
                                  </button>
                                )
                    })
                              }
                            </div>
                          )
                        }
                      </div>
                    )
                })
                  }
                </nav>
              </div>
            </aside>

            {/* Main Content */}
            <div class="flex-1">
              <div class="roadmap-timeline pb-[70vh]">
                {
                  roadmapData.map((section, sectionIndex) => {
                const sectionProgress = calculateProgress(section)
                const sectionStatus = getStatus(sectionProgress)

                return (
                    <div
                      class="roadmap-section mb-12"
                      data-section={section.id}
                    >
                      {/* Section Header */}
                      <div class="section-header mb-8">
                        <div class="mb-3">
                          <h2 class="font-supermolot text-3xl font-bold mb-2">
                            {section.section}
                          </h2>
                          {
                            section.description && (
                              <p class="text-zinc-400">{section.description}</p>
                            )
                          }
                        </div>

                        {/* Progress Bar */}
                        <div class="flex items-center gap-4 mt-4">
                          <div class="flex-1 bg-zinc-700 h-2">
                            <div
                              class="h-2 transition-all duration-500 bg-accent-500"
                              style={`width: ${sectionProgress}%;`}
                            >
                            </div>
                          </div>
                          <span class="text-sm text-zinc-400">{sectionProgress}%</span>
                        </div>
                      </div>

                      {/* Subsections */}
                      <div class="subsections-container space-y-6">
                        {
                          section.subsections && section.subsections.length > 0
                    ? (
                      section.subsections.map((subsection: any) => {
                        const subsectionProgress = calculateSubsectionProgress(
                          subsection,
                        )
                        const subsectionStatus = getStatus(subsectionProgress)

                        return (
                            <div
                              class="subsection-wrapper"
                              data-subsection={subsection.id}
                            >
                              <div class="subsection bg-black p-6 border-2 border-zinc-800">
                                <div class="subsection-header mb-4">
                                  <div class="flex items-center gap-4 mb-2">
                                    <div
                                      class={`w-3 h-3  ${
                                        subsectionStatus === "completed"
                                          ? "bg-accent-500"
                                          : "bg-zinc-400"
                                      }`}
                                    >
                                    </div>
                                    <h3 class="text-xl font-supermolot font-semibold">
                                      {subsection.subsection}
                                    </h3>
                                  </div>

                                  {
                                    subsection.description && (
                                      <p class="text-zinc-400 text-sm mb-3">
                                        {subsection.description}
                                      </p>
                                    )
                                  }

                                  {/* Subsection Progress Bar */}
                                  <div class="flex items-center gap-4">
                                    <div class="flex-1 bg-zinc-700 h-1.5">
                                      <div
                                        class="h-1.5 transition-all duration-500 bg-accent-500"
                                        style={`width: ${subsectionProgress}%;`}
                                      >
                                      </div>
                                    </div>
                                    <span class="text-xs text-zinc-500">{subsectionProgress}%</span>
                                  </div>
                                </div>

                                {/* Milestones (always visible) */}
                                <div
                                  class="milestones-container mt-4 pt-4 border-t-2 border-zinc-800"
                                  data-milestones={subsection.id}
                                >
                                  {
                                    subsection.milestones
                            && subsection.milestones.length > 0
                          ? (
                                      <ul class="space-y-2">
                                        {
                                          subsection.milestones.map((
                            milestone: any,
                          ) => (
                                            <li class="flex items-start gap-4">
                                              {
                                                /* Display the appropriate icon based on completion status */
                                              }
                                              {
                                                milestone.markComplete
                              ? (
                                milestone.completeIcon?.fields?.file
                                    ?.url
                                  ? (
                                                  <img
                                                    src={milestone.completeIcon.fields.file.url
                                                      .startsWith("//")
                                                    ? `https:${milestone.completeIcon.fields.file.url}`
                                                    : milestone.completeIcon.fields.file
                                                      .url}
                                                    alt="Complete"
                                                    class="w-6 h-6 mt-0.5 flex-shrink-0"
                                                  />
                                                )
                                  : (
                                                  <div class="w-6 h-6 mt-0.5 flex-shrink-0 bg-green-500" />
                                                )
                              )
                              : (
                                milestone.incompleteIcon?.fields
                                    ?.file
                                    ?.url
                                  ? (
                                                  <img
                                                    src={milestone.incompleteIcon.fields.file
                                                      .url
                                                      .startsWith("//")
                                                    ? `https:${milestone.incompleteIcon.fields.file.url}`
                                                    : milestone.incompleteIcon.fields.file
                                                      .url}
                                                    alt="Incomplete"
                                                    class="w-6 h-6 mt-0.5 flex-shrink-0 opacity-50"
                                                  />
                                                )
                                  : (
                                                  <div class="w-6 h-6 mt-0.5 flex-shrink-0 border-2 border-zinc-400" />
                                                )
                              )
                                              }
                                              <div class="flex-1">
                                                <span
                                                  class={`${
                                                    milestone.markComplete
                                                      ? "text-zinc-300"
                                                      : "text-zinc-500"
                                                  }`}
                                                >
                                                  {milestone.milestone}
                                                </span>
                                                {
                                                  milestone.description
                                && (
                                                    <p class="text-sm text-zinc-600 mt-1">
                                                      {milestone.description}
                                                    </p>
                                                  )
                                                }
                                              </div>
                                            </li>
                                          ))
                                        }
                                      </ul>
                                    )
                          : (
                                      <p class="text-zinc-500 italic">
                                        No milestones defined yet.
                                      </p>
                                    )
                                  }
                                </div>
                              </div>
                            </div>
                          )
                      })
                    )
                    : (
                            <div class="text-zinc-500 italic">
                              No detailed subsections available yet. Check back soon!
                            </div>
                          )
                        }
                      </div>
                    </div>
                  )
              })
                }
              </div>
            </div>
          </div>
        </div>
      )
    }
  </ContainedSection>
</AnimationLayout>

<script>
function initializeNavigation() {
  function toggleSection(sectionId: string) {
    const subsectionsContainers = document.querySelectorAll(`[data-subsections="${sectionId}"]`)
    const toggleIcons = document.querySelectorAll(
      `[data-toggle-section="${sectionId}"] .toggle-icon`,
    )

    if (subsectionsContainers.length > 0 && toggleIcons.length > 0) {
      const isAnyVisible = Array.from(subsectionsContainers).some(container =>
        !container.classList.contains("hidden")
      )

      if (!isAnyVisible) {
        document.querySelectorAll("[data-subsections]").forEach(container => {
          container.classList.add("hidden")
        })
        document.querySelectorAll(".toggle-icon").forEach(icon => {
          icon.classList.remove("rotate-180")
        })

        subsectionsContainers.forEach(container => {
          container.classList.remove("hidden")
        })
        toggleIcons.forEach(icon => {
          icon.classList.add("rotate-180")
        })
      } else {
        subsectionsContainers.forEach(container => {
          container.classList.add("hidden")
        })
        toggleIcons.forEach(icon => {
          icon.classList.remove("rotate-180")
        })
      }
    }
  }

  // Clean up existing event listeners by cloning elements
  const toggleButtons = document.querySelectorAll(".section-toggle")
  toggleButtons.forEach(button => {
    const newButton = button.cloneNode(true) as HTMLElement
    button.parentNode?.replaceChild(newButton, button)
  })

  const sectionNavItems = document.querySelectorAll(".section-nav-item")
  sectionNavItems.forEach(item => {
    const newItem = item.cloneNode(true) as HTMLElement
    item.parentNode?.replaceChild(newItem, item)
  })

  const subsectionNavItems = document.querySelectorAll(".subsection-nav-item")
  subsectionNavItems.forEach(item => {
    const newItem = item.cloneNode(true) as HTMLElement
    item.parentNode?.replaceChild(newItem, item)
  })

  // Get fresh references and add event listeners
  const newToggleButtons = document.querySelectorAll(".section-toggle")
  newToggleButtons.forEach(button => {
    button.addEventListener("click", (e) => {
      e.stopPropagation()
      const sectionId = button.getAttribute("data-toggle-section")
      toggleSection(sectionId || "")
    })
  })

  const newSectionNavItems = document.querySelectorAll(".section-nav-item")
  newSectionNavItems.forEach(item => {
    item.addEventListener("click", () => {
      const sectionId = item.getAttribute("data-section-id")
      const sectionElement = document.querySelector(`[data-section="${sectionId}"]`)

      if (sectionElement) {
        const rect = sectionElement.getBoundingClientRect()
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop
        const targetPosition = rect.top + scrollTop - 100

        window.scrollTo({
          top: targetPosition,
          behavior: "smooth",
        })
      }

      toggleSection(sectionId || "")
    })
  })

  const newSubsectionNavItems = document.querySelectorAll(".subsection-nav-item")
  newSubsectionNavItems.forEach(item => {
    item.addEventListener("click", (e) => {
      e.stopPropagation()
      const subsectionId = item.getAttribute("data-subsection-id")
      const subsectionElement = document.querySelector(`[data-subsection="${subsectionId}"]`)

      if (subsectionElement) {
        const rect = subsectionElement.getBoundingClientRect()
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop
        const targetPosition = rect.top + scrollTop - 100

        window.scrollTo({
          top: targetPosition,
          behavior: "smooth",
        })

        const parentSection = item.closest(".section-nav")
        const parentSectionContainer = parentSection?.querySelector(".flex")
        if (parentSectionContainer) {
          document.querySelectorAll(".section-nav .flex").forEach(navContainer => {
            navContainer.classList.remove("bg-zinc-800")
          })
          parentSectionContainer.classList.add("bg-zinc-800")
        }

        document.querySelectorAll(".subsection-nav-item").forEach(navItem => {
          navItem.classList.remove("bg-zinc-800")
        })
        item.classList.add("bg-zinc-800")
      }
    })
  })
}

document.addEventListener("astro:page-load", initializeNavigation)
document.addEventListener("astro:after-swap", initializeNavigation)
initializeNavigation()
</script>

<style>
.roadmap-content {
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.roadmap-content::-webkit-scrollbar {
  display: none;
}

.roadmap-sidebar {
  align-self: flex-start;
  width: 20rem;
  min-width: 20rem;
}


.roadmap-sidebar nav::-webkit-scrollbar {
  width: 6px;
}

.roadmap-sidebar nav::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.roadmap-sidebar nav::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.roadmap-sidebar nav::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.2);
}



@media (max-width: 1024px) {
  .roadmap-layout {
    flex-direction: column;
  }
  
  .roadmap-sidebar {
    display: none;
  }
}
</style>
